//
//  Login.m
//  Cunli
//
//  Created by ZhanyaaLi on 15/12/29.
//  Copyright © 2015年 lilubin. All rights reserved.
//

#import "Login.h"
#import "BaseUser.h"
#import "DetailUser.h"
#import "YYModel.h"

#define kLoginStatus @"login_status"        //用户是否登陆
//#define kUserBaseData @"userBasicData"       //用户基本信息
#define kUserBaseData @"userinfo"       //用户基本信息
//#define kUserDetailData @"userDetailData"    //用户详细信息
#define kUserDetailData @"userInfoDic"    //用户详细信息

static BaseUser *curLoginUser;          //当前登陆用户
static DetailUser *curUserDetailData;   //当前登陆用户的详细信息

@implementation Login

/**
 *  是否登录
 *
 *  @return YES:已登录  NO:未登录
 */
+ (BOOL) isLogin
{
    NSNumber *loginStatus = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginStatus];
    
    return loginStatus.boolValue? YES : NO;
}

/**
 *  成功登陆，存储用户数据
 *
 *  @param loginData 用户基本信息
 */
+ (void) doLogin:(NSDictionary *)loginData
{
    if (loginData) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[NSNumber numberWithBool:YES] forKey:kLoginStatus];
        [defaults setObject:loginData forKey:kUserBaseData];
        curLoginUser = [BaseUser yy_modelWithJSON:loginData];
        [defaults synchronize];
//        [self saveLoginData:loginData];
    }else{
        [Login doLogout];
    }

}

//登出
+ (void) doLogout
{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:kUserBaseData];
    [defaults removeObjectForKey:kUserDetailData];
    [defaults setObject:[NSNumber numberWithBool:NO] forKey:kLoginStatus];
    [defaults synchronize];
}

/**
 *  存储用户执行getinfo_member.php之后获取到的用户信息
 *
 *  @param detailData 用户详细信息
 */
+ (void) saveUserDetailData:(NSDictionary *)detailData
{
    if (detailData) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:detailData forKey:kUserDetailData];
        curUserDetailData = [DetailUser yy_modelWithJSON:detailData];
        [defaults synchronize];
    }
    else
    {
        return;
    }
}


/**
 *  获取当前登录用户的基本信息
 *
 *  @return BaseUser
 */
+ (BaseUser *)curLoginBaseUser
{
    if (!curLoginUser) {
        NSDictionary *loginData = [[NSUserDefaults standardUserDefaults] objectForKey:kUserBaseData];
        curLoginUser = loginData? [BaseUser yy_modelWithJSON:loginData]: nil;
    }
    return curLoginUser;

}

/**
 *  获取当前登录用户的详细信息
 *
 *  @return DetailUser
 */
+ (DetailUser *)curLoginDetailUser
{
    if (!curUserDetailData) {
        NSDictionary *detailData = [[NSUserDefaults standardUserDefaults] objectForKey:kUserDetailData];
        curUserDetailData = detailData? [DetailUser yy_modelWithJSON:detailData]: nil;
    }
    return curUserDetailData;
}


@end
